package com.wkh.common.app

import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import java.lang.Exception

/**
 * @des:
 * @author: wkh
 * @version: 1.0.0
 * @date: 3/18/21 21:11
 * @see {@link }
 */
class LayoutHelper {

    companion object {
        private var instance: LayoutHelper? = null
            get() {
                if (field == null) {
                    field = LayoutHelper()
                }
                return field
            }

        @Synchronized
        fun get(): LayoutHelper {
            return instance!!
        }
    }

    private var mLayoutInflater: LayoutInflater? = null

    fun init(context: Context) {
        mLayoutInflater = LayoutInflater.from(context)
    }

    private val viewPool by lazy {
        SparseArray<CacheViewWrapper>()
    }

    /**
     * 同步方法中返回View对象
     */
    fun syncGet(@LayoutRes layoutResId: Int): View {
        checkStatus()
        viewPool.get(layoutResId)?.run {
            viewPool.put(layoutResId, next)
            return cachedView
        }

        mLayoutInflater?.run {
            return inflate(layoutResId, null)
        }

        throw Exception("获取View异常")
    }


    /**
     * 挂起方法中返回View对象
     */
    suspend fun asyncGet(@LayoutRes layoutResId: Int): View {
        return syncGet(layoutResId)
    }

    /**
     * @param layoutResId 要缓存的资源ID
     * @param cacheTimes 需缓存的次数
     */

    fun preLoad(@LayoutRes layoutResId: Int, cacheTimes: Int) {
        checkStatus()
        mLayoutInflater?.run {
            for (index in 0..cacheTimes) {
                doCache(layoutResId, inflate(layoutResId, null))
            }
        }
    }


    fun preLoad(@LayoutRes layoutResId: Int) {
        preLoad(layoutResId, 1)
    }


    fun cacheView(@LayoutRes layoutResId: Int, view: View) {
        view.parent?.run {
            (this as ViewGroup).removeView(view)
        }

        doCache(layoutResId, view)
    }

    @Synchronized
    private fun doCache(@LayoutRes layoutResId: Int, view: View) {
        val cached = viewPool.get(layoutResId)
        val needCache = CacheViewWrapper(view)
        if (cached == null) {
            viewPool.put(layoutResId, needCache)
        } else {
            needCache.next = cached
            viewPool.put(layoutResId, needCache)
        }
    }

    private fun checkStatus() {
        if (mLayoutInflater == null) {
            throw Exception("请先进行初始化操作")
        }
    }
}